﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IndexDefinitionService.cs" company="DST Nexdox">
//   Copyright (c) DST Nexdox. All rights reserved.
// </copyright>
// <summary>
//   Defines the IndexDefinitionService type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Services
{
  using System;
  using System.Linq;
  using DocProcessingRepository.Interfaces;
  using Entities;
  using Exceptions;
  using ServiceInterfaces;

  public class IndexDefinitionService : IIndexDefinitionService
  {
    private readonly IIndexDefinitionRepository indexDefinitionRepository;

    private readonly IUserService userService;

    private readonly IMediaDefinitionAuditService mediaDefinitionAuditService;

    private readonly IMailSortSettingService mailSortSettingService;

    public IndexDefinitionService(IIndexDefinitionRepository indexDefinitionRepository, IUserService userService, IMediaDefinitionAuditService mediaDefinitionAuditService, IMailSortSettingService mailSortSettingService)
    {
      this.indexDefinitionRepository = indexDefinitionRepository;
      this.userService = userService;
      this.mediaDefinitionAuditService = mediaDefinitionAuditService;
      this.mailSortSettingService = mailSortSettingService;
    }

    public void UpdateMailSortSetting(Int32 mediaDefinitionId, Int32 mailSortSettingId)
    {
      try
      {
        Int32? nullableMailSortSettingId;
        String message;

        if (mailSortSettingId != 0)
        {
          nullableMailSortSettingId = mailSortSettingId;
          MailsortSetting mailSortSetting = this.mailSortSettingService.GetMailsortSettings().Single(m => m.MailsortSettingID == mailSortSettingId);
          message = String.Format("MailSortSetting set as '{0}'", mailSortSetting.nexdoxMailsortService);
        }
        else
        {
          nullableMailSortSettingId = null;
          message = "MailSortSetting cleared";
        }

        this.indexDefinitionRepository.UpdateMailSortSetting(mediaDefinitionId, nullableMailSortSettingId);

        ApplicationUser user = this.userService.GetApplicationUser();
        this.mediaDefinitionAuditService.AddAudit(
          mediaDefinitionId,
          user.Id,
          MediaDefinitionAudit.MediaDefinitionAuditType.MailSortSettingUpdated,
          DateTime.Now,
          message);
      }
      catch (Exception e)
      {
        throw new DocProcessingException("Unable to update mail sort setting on media definition", e);
      }
    }
  }
}
